package com.jacky.iot.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.influxdb.client.InfluxDBClient;
import com.jacky.iot.commons.Cmd;
import com.jacky.iot.config.InfluxDbConfig;
import com.jacky.iot.dtos.WebSocketReq;
import com.jacky.iot.dtos.DataFetchWrapper;
import com.jacky.iot.dtos.TimeCmd;
import com.jacky.iot.models.CpuUsage;
import com.jacky.iot.models.FluxQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class CpuUsageService {

    private static final Logger LOG = LoggerFactory.getLogger(CpuUsageService.class);

    private final InfluxDbConfig config;
    private final InfluxDBClient dbClient;

    public CpuUsageService(InfluxDbConfig config, InfluxDBClient dbClient) {
        this.config = config;
        this.dbClient = dbClient;
    }

    public List<CpuUsage> fetchLastData(DataFetchWrapper dfw, TimeCmd windowTC) {
        String timeRange = timeRange(windowTC.getTime(), windowTC.getTimeUnit());
        List<String> fetchFields = Lists.newArrayList(dfw.getTagMap().keySet());
        fetchFields.add(dfw.getTimeField());
        String qryFlux = new FluxQueryBuilder(config.getDatabase())
                .range(timeRange)
                .addTagFilter(dfw.getTagMap())
                .addFieldFilter(dfw.getFetchFields())
                .build(dfw.getMeasurement(), fetchFields);
        if (LOG.isDebugEnabled()) {
            LOG.debug("flux qry:\n{}", qryFlux);
        }
        return dbClient.getQueryApi().query(qryFlux, config.getOrg(), CpuUsage.class);
    }

    private String timeRange(int lastTime, TimeUnit timeUnit) {
        String timeSuffix = "s";
        switch (timeUnit) {
            case HOURS -> timeSuffix = "h";
            case SECONDS -> timeSuffix = "s";
            case MINUTES -> timeSuffix = "m";
            default -> timeSuffix = "s";
        }
        return -lastTime + timeSuffix;
    }

    public static void main(String[] args) {
        DataFetchWrapper dfw = new DataFetchWrapper();
        dfw.setMeasurement("cup_usage");
        dfw.setFetchFields(Lists.newArrayList("usage", "system"));
        Map<String, Object> tagMap = Maps.newHashMap();
        tagMap.put("host", "192.168.56.1");
        tagMap.put("cpu_core", "total");
        dfw.setTagMap(tagMap);

        WebSocketReq dfc = new WebSocketReq();
        dfc.setCmd(Cmd.FETCH_DATA);
        dfc.setFetchId("159");
        dfc.setDfw(dfw);
        dfc.setWindowTC(new TimeCmd(5, TimeUnit.MINUTES));
        dfc.setIntervalTC(new TimeCmd(10, TimeUnit.SECONDS));

        Gson gson = new Gson();
        System.out.println(gson.toJson(dfc));

    }
}
